#include "queue.h"

// 模块内方法声明
void _queue_push(Queue* thiz, u32 data);
u32 _queue_poll(Queue* thiz);
Interator* _queue_create_interator(Queue* thiz);
u32 _interator_next(Interator* thiz);

// 模块接口实现
Queue* create_queue()
{
	// 初始化队列
	Queue* queue            = (Queue*) malloc(sizeof(Queue));
	Node* node              = create_node();
	
	queue->head             = node;
	queue->tail             = node;
	queue->length           = 0;
	queue->push             = _queue_push;
	queue->poll             = _queue_poll;
	queue->create_interator = _queue_create_interator;
	return queue;
}

Node* create_node()
{
	Node* node = (Node*) malloc(sizeof(Node));
	node->data = 0;
	return node;
}

// 模块内方法实现
void _queue_push(Queue* thiz, u32 data)
{
	Node* node = create_node();
	node->data = data;

	thiz->tail->next = node;
	thiz->tail       = node;
	(thiz->length)++;
}

u32 _queue_poll(Queue* thiz)
{
	u32 result;
	Node* new_head;
	//队列已空
	if(thiz->length == 0)
	{
		return ERROR_DATA;
	}

	new_head = thiz->head->next;
	result = thiz->head->data;
	//清空即将释放指针指向的内存对象
	thiz->head->data = 0;
	thiz->head->next = 0;
	//free函数只释放指针，不清空数据
	free(thiz->head);
	thiz->head = new_head;
	(thiz->length)--;
	return result;
}

Interator* _queue_create_interator(Queue* thiz)
{
	Interator* interator = (Interator*) malloc(sizeof(Interator));

	interator->queue    = thiz;
	interator->cru_node = thiz->head;
	interator->next     = _interator_next;

	return interator;
}

u32 _interator_next(Interator* thiz)
{
	u32 result;

	// 遍历已完成
	if(thiz->cru_node == thiz->queue->tail->next)
	{
		return ERROR_DATA;
	}

	result = thiz->cru_node->data;
	thiz->cru_node = thiz->cru_node->next;

	return result;
}
